/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package job.manager.security.connector;

import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import job.manager.db.ec.UsersEB;
import job.manager.db.sb.UserRemote;
import job.manager.security.app.AppUser;
import job.manager.security.interfaces.AppUserInt;
import job.manager.security.interfaces.UserDataConnectorInt;

public class UserDataConnector implements UserDataConnectorInt {


    public AppUserInt findUser(String userName) {
        UserRemote userBean = this.lookupUserBean();
        UsersEB user = userBean.findUser(userName);
        Set<String> roles = new HashSet<String>();
        if(user.getIsAdmin()) {
            roles.add("ROLE_ALLACCESS");
        }
        else {
          roles.add("ROLE_URLACCESS");
        }

        return new AppUser(user.getUserName(),user.getPassword(),user.getEmail(),roles);

    }

    private UserRemote lookupUserBean() {
        try {
            Context c = new InitialContext();
            return (UserRemote) c.lookup("java:comp/env/UserBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

/*    private UserRemote lookupUserBean() {
        try {
            Context c = new InitialContext();
            return (UserRemote) c.lookup("java:comp/env/UserBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }*/

}
